import * as qiniu from 'qiniu-js';
import { UploadCompleteData } from 'qiniu-js/esm/api';
import { UploadProgress, ProgressCompose } from 'qiniu-js/esm/upload/base';
import { QiniuError, QiniuNetworkError, QiniuRequestError } from 'qiniu-js/esm/errors';
import cookie from 'js-cookie';
import qs from 'qs';

/**
 * 更新state
 * @param type reducers中的方法名
 */
export const createAction =
  (type: string) =>
  (payload = {}) => ({ type, payload });

type qiniuUploadOptions = {
  token: string;
  bucket: string;
  onError?: (e: QiniuError | QiniuNetworkError | QiniuRequestError) => void;
  onProgress?: (progress: ProgressCompose) => void;
  onSuccess?: (res: UploadCompleteData) => void;
};
export function qUplad(file: File, options: qiniuUploadOptions) {
  const uploadName = `/${+new Date()}/${file.name}`;
  const observer = qiniu.upload(file, uploadName, options.token, {}, { useCdnDomain: true });
  const subscription = observer.subscribe(
    (progress: UploadProgress) => options?.onProgress?.(progress.total) as any,
    options?.onError as any,
    (res) => {
      options?.onSuccess?.(res);
      subscription.unsubscribe();
    },
  );
}
/**
 * 获取route params
 * @returns
 */
export const routeParamsGet = (): string => (window.location.hash.split('?')[0] || '').split('/').slice(-1)[0];

/**
 * 获取url参数
 * @param str
 * @returns
 */
export const urlSearchGet = (str: string) => {
  const strArr = (str.split('?')[1] || '').split('&');
  const params = {};
  strArr.forEach((strItem) => {
    const [key, value] = strItem.split('=');
    params[key] = decodeURIComponent(value);
  });
  return params;
};

/**
 * 导出excel
 * @param url
 * @param params
 */
export const exportExcel = (url: string, params: any): void => {
  const token = { token: cookie.get('token'), sid: cookie.get('sid') };
  const $url = `${API_HOST}${url}?${qs.stringify(Object.assign(token, params))} `;
  const aele = document.createElement('a');
  aele.href = $url;
  Object.assign(aele, {
    target: '_blank',
    rel: 'noopener',
  });
  aele.style.visibility = 'hidden';
  document.body.appendChild(aele);
  aele.click();
  setTimeout(() => {
    aele.remove();
  });
};
